import axios from 'axios'//引入axios
import {examineValue,loading} from '@/tools/util.js'


const errorFn = (err) => {
  if (err.toString().includes('timeout')) {
    console.error('请求超时')
  }
  if (err && err.response) {
    console.error(err.message)
  }
  return Promise.reject(err)
}
const $ajax = axios.create({
  headers: {},
  // baseURL: BASE_URL,
  timeout: 60000,
  withCredentials: true,
})
$ajax.interceptors.request.use(
  (config) => {
    // 这里一个token，你需要在这里取到你设置好的token的值
    let token = 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMTMzNjE4MjM0MTQ4MDU0NjMwNiIsInVzZXJfbmFtZSI6Imx5biIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2Nzg0MzM3MjgsImF1dGhvcml0aWVzIjpbInN1cGVyX2FkbWluIl0sImp0aSI6ImVjMjUyNjcwLTY3ZGYtNGZlMC05NGEyLWExNDc0NTBhYWQ0YiIsImVtYWlsIjoiMTMyNjU3OTM3MEBxcS5jb20iLCJjbGllbnRfaWQiOiJtYXRjbG91ZC1wbHVzIn0.UkQqO6Qw7iJIdY6ag8nDZdmJuGQRarNhjWU4AOSs6KN5KnOOHUBijUMCfgs9HBmz_f39VPpIs1WycYmmpyMAc5T4a12PYsUu3h3IrGWaC1rsgJhDNzdhvidjgoucS4zxy2X-LQr86X9HOCkvJs71QT5Q-9v0YBOGQ8wKt_PCJ0wCgYJUdonnyXu64FE6nKuZk2T06M9YaYPOl9MD8WbVOHa0h4cP_GmzDS8SkUwAVl99PWU4D9-fE9s3dELjRSJ9OfuopRvRaKCMf-u-JeB2bwSUkqzIIsbqz4cuHu9sl0k9eRxEGnrEe_XUlDcLu1JbQ8ZfMEo9yz3IBhHZ01k_qg'
    let timestamp = new Date().getTime()
    config.headers.Authorization = 'Bearer ' + token
    // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
    if (config.url.includes('?')) {
      config.url += `&timestamp=${timestamp}`
    } else {
      config.url += `?timestamp=${timestamp}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
$ajax.interceptors.response.use((response) => {
  return response
}, errorFn)
// 拼接
function disposeParam(url, param) {
  if (examineValue(param)) {
    for (let key in param) {
      url = url.replace('{' + key + '}', param[key])
    }
  }
  return url
}

export default function ajax(
  {
    url,
    headers = {},
    data = {},
    type = 'get',
    isLoad = false,
    responseType = '',
    timeout,
    isData = true,
    fileNameReturn = false,
  },
  isParams = false
) {
  return new Promise((resolve, reject) => {
    let requestAddress = ''
    if(typeof url === 'object'){
      requestAddress = url.url
    }else {
      requestAddress = url
    }
    if (requestAddress.indexOf('{') !== -1) {
      requestAddress = disposeParam(requestAddress, data)
    }
    let loadInstance = null
    let obj = {
      url: requestAddress,
      method: type,
      headers: headers,
      responseType,
      timeout: timeout,
    }
    if (isParams) {
      obj.traditional = true
      obj.params = data
    } else if (isData) {
      obj.data = data
    }
    if (isLoad) {
      loadInstance = new loading()
    }
    $ajax(obj)
      .then(function (res) {
        let result = res.data
        if (result.code && result.code !== 0) {
          if (result.code > 70000000) {
            reject(res)
            return
          }
          // 121 的情况下为token失效
          if (result.code === 121) {
            console.error('更新token');
          } else if (
            [1310, 2202, 2203].includes(result.code)
          ) {
            console.error('账户没权力换个token，手机邮箱用过了');
            resolve(result)
            return
          } else {
            console.error('接口报错了');
          }
          console.error(url, data, res, window.location.href)
          reject(res)
          return false
        } else {
          resolve(fileNameReturn ? res : result)
        }
      })
      .catch(function (err) {
        console.error(url, data, err, window.location.href)
        reject(err)
      })
      .finally(function () {
        if (isLoad) {
          loadInstance.close()
        }
      })
  })
}

